﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VCommons.Encryptor;
using VCommons;
using System.Web;
using System.Collections.Specialized;
using System.Configuration;
using tenpay;

namespace OnlinePayment
{
    /// <summary>
    /// 第三方回写操作（从第三方返回的信息，根据信息去执行下一步操作）
    /// 最优实现：需要与具体支付业务无关，与数据库无关
    /// </summary>
    public class OnlineReturn
    {

        #region Events
        /// <summary>
        /// 第三方支付成功
        /// </summary>
        public event Action OnlineSuccess;
        public void OnOnlineSuccess()
        {
            if (this.OnlineSuccess != null)
                this.OnlineSuccess();
        }
        #endregion
        string userID = SessionAction.ReadSession("UserID");
        HttpRequest Request = HttpContext.Current.Request;
        HttpResponse Response = HttpContext.Current.Response;
        string success_Url = "/order/success";
        string fail_Url = "/order/fail";
        #region 在线支付返回

        #region 支付宝回写操作
        /// <summary>
        /// 支付宝Notify回写操作
        /// </summary>
        public void AlipayNotify()
        {
            string exchangeID = Request.Params["out_trade_no"].ToString();
            bool ret = AlipayNotifyParam(userID, exchangeID, Request.Params["notify_id"].ToString(), Request.Params["sign"].ToString(), Request.QueryString, HttpContext.Current);

            if (ret)
            {
                //成功
                #region 改订单状态
                OnOnlineSuccess();
                #endregion
                Response.Write("success");
            }
            else
            {
                //失败
                Response.Write("fail");
            }
        }

        /// <summary>
        /// 支付宝Notify回写参数
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="exchangeID"></param>
        /// <param name="notify_id"></param>
        /// <param name="sign"></param>
        /// <param name="coll"></param>
        /// <param name="http"></param>
        /// <returns></returns>
        public bool AlipayNotifyParam(string userID, string exchangeID, string notify_id, string sign, NameValueCollection coll, HttpContext http)
        {
            string alipayNotifyURL = "http://notify.alipay.com/trade/notify_query.do?";
            string partner = ConfigurationManager.AppSettings["AlipayPartner"].ToString();
            string key = ConfigurationManager.AppSettings["AlipayKey"].ToString();
            string _input_charset = ConfigurationManager.AppSettings["AlipayInputCharSet"].ToString();
            alipayNotifyURL = alipayNotifyURL + "&partner=" + partner + "&notify_id=" + notify_id;
            string responseTxt = AliPay.Get_Http(alipayNotifyURL, 120000);

            int i;
            String[] requestarr = coll.AllKeys;

            //进行排序；
            string[] Sortedstr = AliPay.BubbleSort(requestarr);

            //构造待md5摘要字符串 ；
            StringBuilder prestr = new StringBuilder();

            for (i = 0; i < Sortedstr.Length; i++)
            {
                if (http.Request.Params[Sortedstr[i]] != "" && Sortedstr[i] != "sign" && Sortedstr[i] != "sign_type")
                {
                    if (i == Sortedstr.Length - 1)
                    {
                        prestr.Append(Sortedstr[i] + "=" + http.Request.Params[Sortedstr[i]]);
                    }
                    else
                    {
                        prestr.Append(Sortedstr[i] + "=" + http.Request.Params[Sortedstr[i]] + "&");
                    }
                }
            }

            prestr.Append(key);

            //生成Md5摘要；
            string mysign = AliPay.GetMD5(prestr.ToString(), _input_charset);


            if (mysign == sign && responseTxt == "true")
                return true;
            else
                return false;
        }

        /// <summary>
        /// 支付宝Return回写操作
        /// </summary>
        public void AlipayReturn()
        {

            string exchangeID = Request.Params["out_trade_no"].ToString();
            bool ret = AlipayReturnParam(userID, exchangeID, Request.Params["notify_id"].ToString(), Request.Params["sign"].ToString(), Request.QueryString, System.Web.HttpContext.Current);
            if (ret)
            {

                //成功
                #region 改订单状态

                #endregion
                Response.Redirect(success_Url);
                Response.Flush();
                Response.Close();
            }
            else
            {
                Response.Redirect(fail_Url);
                Response.Flush();
                Response.Close();
            }
        }


        /// <summary>
        /// 支付宝Return回写参数
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="exchangeID"></param>
        /// <param name="notify_id"></param>
        /// <param name="sign"></param>
        /// <param name="coll"></param>
        /// <param name="http"></param>
        /// <returns></returns>
        public bool AlipayReturnParam(string userID, string exchangeID, string notify_id, string sign, NameValueCollection coll, HttpContext http)
        {
            string alipayNotifyURL = "http://notify.alipay.com/trade/notify_query.do?";
            string partner = ConfigurationManager.AppSettings["AlipayPartner"].ToString();
            string key = ConfigurationManager.AppSettings["AlipayKey"].ToString();
            string _input_charset = ConfigurationManager.AppSettings["AlipayInputCharSet"].ToString();
            alipayNotifyURL = alipayNotifyURL + "&partner=" + partner + "&notify_id=" + notify_id;
            string responseTxt = AliPay.Get_Http(alipayNotifyURL, 120000);

            int i;
            String[] requestarr = coll.AllKeys;

            //进行排序；
            string[] Sortedstr = AliPay.BubbleSort(requestarr);

            //构造待md5摘要字符串 ；
            StringBuilder prestr = new StringBuilder();

            for (i = 0; i < Sortedstr.Length; i++)
            {
                if (http.Request.QueryString[Sortedstr[i]] != "" && Sortedstr[i] != "sign" && Sortedstr[i] != "sign_type")
                {
                    if (i == Sortedstr.Length - 1)
                    {
                        prestr.Append(Sortedstr[i] + "=" + http.Request.QueryString[Sortedstr[i]]);
                    }
                    else
                    {
                        prestr.Append(Sortedstr[i] + "=" + http.Request.QueryString[Sortedstr[i]] + "&");
                    }
                }
            }

            prestr.Append(key);

            //生成Md5摘要；
            string mysign = AliPay.GetMD5(prestr.ToString(), _input_charset);

            if (mysign == sign && responseTxt == "true")   //验证支付发过来的消息，签名是否正确
                return true;
            else
                return false;
        }
        #endregion

        #region 财付通回写操作
        /// <summary>
        /// 财付通回写操作
        /// </summary>
        /// <returns></returns>
        public void TenpayReturn()
        {
            PayResponseHandler resHandler = new PayResponseHandler(System.Web.HttpContext.Current);

            string exchangeID = resHandler.getParameter("transaction_id");
            bool ret = TenpayReturnParam(userID, exchangeID, System.Web.HttpContext.Current);

            if (ret)
            {
                //成功
                #region 改订单状态

                #endregion
                Response.Redirect(success_Url);
                Response.Write("success");
            }
            else
            {
                Response.Redirect(fail_Url);
                Response.Write("fail");
            }
        }
        /// <summary>
        /// 财付通回写参数
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="exchangeID"></param>
        /// <param name="http"></param>
        /// <returns></returns>
        public bool TenpayReturnParam(string userID, string exchangeID, System.Web.HttpContext http)
        {
            //密钥
            string key = ConfigurationManager.AppSettings["TenpayKey"].ToString();
            //创建PayResponseHandler实例
            PayResponseHandler resHandler = new PayResponseHandler(http);
            resHandler.setKey(key);

            //交易单号
            string transaction_id = resHandler.getParameter("transaction_id");
            //金额金额,以分为单位
            string total_fee = resHandler.getParameter("total_fee");

            //支付结果
            string pay_result = resHandler.getParameter("pay_result");


            if (resHandler.isTenpaySign() && "0".Equals(pay_result))
                return true;
            else
                return false;
        }
        #endregion

        #region 银联回写

        /// <summary>
        /// 银联回写操作
        /// </summary>
        /// <returns></returns>
        public void ChinaPayRetUrl()
        {
            int userID = Convert.ToInt32(Utility.DecryptString(Request.Params["Priv1"].ToString()).Split('|')[0]);
            int orderID = Convert.ToInt32(Utility.DecryptString(Request.Params["Priv1"].ToString()).Split('|')[1].Split(',')[1]);
            string orderIDs = Utility.DecryptString(Request.Params["Priv1"].ToString()).Split('|')[1];
            int rpID = Convert.ToInt32(Utility.DecryptString(Request.Params["Priv1"].ToString()).Split('|')[2]);

            string exchangeID = Request.Params["OrdId"].ToString();
            bool ret = ChinaPayRetUrlParam(userID, orderID, rpID, exchangeID, Request.Params["MerId"].ToString(), Request.Params["BusiId"].ToString(), Request.Params["OrdId"].ToString(), Request.Params["OrdAmt"].ToString(), Request.Params["CuryId"].ToString(), Request.Params["Version"].ToString(), Request.Params["GateId"].ToString(), Request.Params["ShareType"].ToString(), Request.Params["ShareData"].ToString(), Request.Params["Priv1"].ToString(), Request.Params["CustomIp"].ToString(), Request.Params["PayStat"].ToString(), Request.Params["PayTime"].ToString(), Request.Params["ChkValue"].ToString());

            if (ret)
            {
                Response.Redirect(success_Url);
                Response.Write("success");
            }

            else
            {
                Response.Redirect(fail_Url);
                Response.Write("fail");
            }
        }

        /// <summary>
        /// 银联回写参数
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="exchangeID"></param>
        /// <param name="MerId"></param>
        /// <param name="BusiId"></param>
        /// <param name="OrdId"></param>
        /// <param name="OrdAmt"></param>
        /// <param name="CuryId"></param>
        /// <param name="Versions"></param>
        /// <param name="GateId"></param>
        /// <param name="ShareType"></param>
        /// <param name="ShareData"></param>
        /// <param name="Priv1"></param>
        /// <param name="CustomIp"></param>
        /// <param name="PayStat"></param>
        /// <param name="PayTime"></param>
        /// <param name="ChkValue"></param>
        /// <returns></returns>
        public bool ChinaPayRetUrlParam(int userID, int orderID, int rpID, string exchangeID, string MerId, string BusiId, string OrdId, string OrdAmt, string CuryId, string Versions, string GateId, string ShareType, string ShareData, string Priv1, string CustomIp, string PayStat, string PayTime, string ChkValue)
        {
            ChinaPayUtils.pubKeyPath = ConfigurationManager.AppSettings["ChinaPayPubKeyPath"].ToString();
            string plainData = MerId + BusiId + OrdId + OrdAmt + CuryId + Versions + GateId + ShareType + ShareData + Priv1 + CustomIp + PayStat + PayTime;
            string i = ChinaPayUtils.checkData(plainData, ChkValue);


            if (PayStat == "1001" && i == "0")
            {

                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #endregion

    }
}
